package com.ljc.cjgl.controller.bbs;

import com.ljc.cjgl.custom.TablePageable;
import com.ljc.cjgl.custom.TableResult;
import com.ljc.cjgl.entitiy.bbs.Article;
import com.ljc.cjgl.form.bbs.ArticleForm;
import com.ljc.cjgl.service.bbs.ArticleService;
import org.abyss.data.specifications.Rule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashSet;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author: JavaJun
 * Date: 2019-05-16 19:44
 */
@Controller
@RequestMapping(value = "/bbs/manage")
public class BbsManageController {

    @Autowired
    private ArticleService articleService;

    @GetMapping(value = "")
    public String manageView(ModelMap map) {
        return "bbs/article/manage";
    }

    @RequestMapping(value="/page")
    @ResponseBody
    public Object page(TablePageable pageable, ArticleForm form) {
        PageRequest pageRequest = pageable.bulidPageRequest();
        HashSet<Rule> rules=new HashSet<>();
        String title = form.getTitle();
        Integer testId = form.getId();
        String search = form.getSearch();
        if(StringUtils.hasText(title)) {
            rules.add(Rule.property("title").contain(title));
        }
        if(testId!=null) {
            rules.add(Rule.property("id").equal(testId));
        }
        if(StringUtils.hasText(search)) {
            HashSet<Rule> rules2=new HashSet<>();
            rules2.add(Rule.property("title").contain(search));
            rules2.add(Rule.property("sysUser.name").contain(search));
           /* rules2.add(Rule.property("title").contain(search));
            rules2.add(Rule.property("explain").contain(search));*/
            rules.add(Rule.or(rules2));
        }
        Specification<Article> specification = Rule.and(rules).toSpecification();
        Page<Article> page=articleService.findAll(specification,pageRequest);
        return TableResult.bulidPageResult(page);
    }


    @RequestMapping(value="/delete")
    @ResponseBody
    public Object delete(@RequestBody List<Article> articles) {
        if(articleService.delete(articles)) {
            return TableResult.bulidResult(true, "数据删除成功");
        }else {
            return TableResult.bulidResult(false, "数据删除失败");
        }
    }
}
